// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

String.prototype.stringToDate = function () {
    return new Date(Date.parse(this.replace(/-/g, "/")));
}

function dateFormat(value) {
    if (value && (typeof value) == 'string')
        return (new Date(value.stringToDate())).Format('yyyy-MM-dd');
    else
        return (new Date(value)).Format('yyyy-MM-dd');
}

function datetimeFormat(value) {
    if (value && (typeof value) == 'string')
        return (new Date(value.stringToDate())).Format('yyyy-MM-dd hh:mm');
    else
        return (new Date(value)).Format('yyyy-MM-dd hh:mm');
}

//格式化时间
function fmDate(value) {
    return value == null ? "" : dateFormat(value);
}

//生成序号
function fmIndex(value, row, index) {
    return index + 1;
}

//bootstrap table load data
function ajaxRequest(params) {
    getAsyncJSON(params.url, params.data, function (data) {
        params.success(data);
    });
}

//拼接查询字符串
function getQueryParams(baseUrl, barName) {
    var queryParams = {};
    if (barName)
        $("#" + barName + " input,#" + barName + " select").each(function (i, n) {
            if ($(n).attr("name") && "" != $.trim($(n).val())) {
                queryParams[$(n).attr("name")] = $.trim($(n).val());
            }
        });
    return concatURLOrg(baseUrl, queryParams);
}
//生成Json串
function generateJSONObj(barName, exclude) {
    var arr = [];
    if (barName) {
        $("#" + barName + " input,#" + barName + " select,#" + barName + " textarea").each(function (i, n) {
            if ($(n).attr("name") && "" != $.trim($(n).val())) {
                if (exclude && exclude[$(n).attr("name")]) {
                    return true;
                }
                arr.push({data: $.trim($(n).val()), type: $(n).attr('name')});
            }
        })
    }
    return arr;
}
//生成Json串
function generateJSONObj2(barName, exclude) {
    var arr = [];
    if (barName) {
        $("#" + barName + " input,#" + barName + " select,#" + barName + " textarea").each(function (i, n) {
            if ($(n).attr("name")) {
            	if($(n).attr("nullable")){
            		arr.push({data: $.trim($(n).val()), type: $(n).attr('name')});
            	}else{
            		if("" != $.trim($(n).val())){
            			if (exclude && exclude[$(n).attr("name")]) {
                            return true;
                        }
                        arr.push({data: $.trim($(n).val()), type: $(n).attr('name')});
            		}
            	}
            }
        })
    }
    return arr;
}
//重置Form
function resetForm(barName, excludeList) {
    if (barName) {

        $("#" + barName + " input").each(function (i, n) {
            if(excludeList && excludeList[$(this).attr('id')])
                return;
            $(n).val("");
        })

        $("#" + barName + " select").each(function (i, n) {
            $(n).selectpicker('val', '');
        })
    }
}
//初始化简历筛选框
function initResumeFilter(barName, obj) {
    if (barName) {
        if (obj) {
            for (v in obj) {
                var component = $('#ip' + v.substring(0, 1).toUpperCase() + v.substring(1))
                if (component.hasClass('selectpicker')) {
                    component.selectpicker('val', obj[v])
                } else {
                    component.val(obj[v])
                }
            }
        }
    }
}
//组合url
function concatURLOrg(url, data) {
    var u = url;
    if (u.indexOf('?') == -1) {
        u += '?';
    } else {
        u = u.substr(0, u.indexOf('?') + 1);
    }

    if (typeof data == 'string')
        u += decodeURIComponent(data);
    else
        u += decodeURIComponent($.param(data, true));
    return u;
}

//拼接url和参数(不截断原url)
function concatURLParams(url, data) {
    u = url;
    if (u.indexOf('?') == -1) {
        u += '?';
    } else {
        u += '&';
    }

    if (typeof data == 'string')
        u += decodeURIComponent(data);
    else
        u += decodeURIComponent($.param(data, true));
    return u;
}

//url拼接辅助
function _getRandUrl(url) {
    return encodeURI(url + (url.indexOf("?") == -1 ? "?" : "&"));
}

//定义当前总共打开过罩层的数量，当为1时关闭
var maskQty = 0;
/**
 * ajax异步执行
 * @param {String} url
 * @param {Object} data
 * dep:jquery,handleJSONResult()
 */
function getAsyncJSON(url, data, success, msg, error) {
    $(function () {
        if (maskQty <= 0) {
            layer.load(0, {shade: [0, 'rgba(0,0,0,0)']});
        }
        maskQty++;
    });
    $.ajax({
        url: _getRandUrl(url),
        data: data,
        type: 'post',
        dataType: 'json',
        complete: function (XHR, textStatus) {
            $(function () {
                if (maskQty == 1) {
                    layer.closeAll();
                }
                maskQty--;
            });

            handleJSONResult(XHR.responseText, success, error, textStatus);
        },
        traditional: true
    });
}


/**
 * 处理后台返回的json消息
 * @param {Object} jsonText
 * @param {Object} success
 * @param {Object} failed
 * @param {Object} error
 * dep:jquery,alertMessage(),handleFieldError()
 */
function handleJSONResult(jsonText, success, error, textStatus) {
    var data = {};
    try {
        data = $.parseJSON(jsonText);
    } catch (e) {
        console.log(e);
        //转型失败
        $(function () {
            layer.msg('加载数据失败!');
        });
        if (!!error)
            error(jsonText);
        return jsonText;
    }

    if (!textStatus || textStatus == "success") {
        if (success)
            success(data);
    } else {
        var errorMsg = handleFieldError(data);
        layer.msg('加载数据失败!');
    }
}

/**
 * 处理错误消息
 * @param {Object} msgs
 * @param {Object} erros
 * dep:jquery
 */
function handleFieldError(erros) {
    var msg = [];
    if (!!erros)
        for (var error in erros)
            msg.push('<strong>' + error + '</strong>  :  ' + erros[error]);
    return msg.join('<br>');
}

/**
 * 提交表单
 * @param {String} selector 选择器字符串
 * @param {Function} onSubmit 提交前执行
 * @param {Function} success 成功后执行
 * @param {Function} failed 失败时执行
 * @param {Function} error 未知错误时执行
 * dep:easyui
 */
function submitFormData(selector, onSubmit, success, error) {
    $(".temp").remove();
    $(selector).ajaxSubmit({
        beforeSubmit: function () {
            if (!!onSubmit)
                onSubmit();
            layer.load(0, {shade: [0, 'rgba(0,0,0,0)']});
            maskQty++;
            return true;
        },
        success: function (data) {
            if (maskQty = 1)
                layer.closeAll();
            maskQty--;
            if (success)
                success(data);
        }
    });
}

/**
 * 将数据读入form中
 * @param {String} selector 选择器字符串
 * @param {Object} data 数据对象
 * @param {String} prefix 表格input name 前缀
 * dep:easyui
 */
function loadFormData(data, prefix, exclude) {
    if (!prefix)
        prefix = '';
    else
        prefix = prefix + '.'
    var obj = {};
    for (v in data) {
        if (exclude && exclude[v])
            continue;
        var component = $('[name="' + prefix + v + '"]')
        component.val(data[v])
    }
}
/**
 * 加载数据到form中，处理了input 以及selectpicker
 * @param data
 */
function loadFormDataWithSelectpicker(data) {
    for (v in data) {
        var component = $('[name="' + v + '"]');
        if (component.hasClass('selectpicker')) {
            component.selectpicker('val', data[v]);
        } else {
            component.val(data[v])
        }
    }
}
/**
 * form表单数据初始化 for AccountProfile
 * @param data
 */
function loadFormDataForAccountProfile(data) {
    var majorTradeFirst = "";
    var tradeFirst = "";
    var majorTradeSecond = "";
    var tradeSecond = "";
    var companyLabels = "";
    $.each(data, function (i, item) {
        if (item.type == 2025)
            $('[name="2025"]').selectpicker('val', item.data);
        if (item.type == 2007)
            $('[name="2007"]').selectpicker('val', item.data);
        if (item.type == 2005)
            tradeFirst = item.data;
        if (item.type == 2030)
            majorTradeFirst = item.data;
        if (item.type == 2034)
            majorTradeSecond = item.data;
        if (item.type == 2035)
            tradeSecond = item.data;
        if (item.type == 2018)
            companyLabels = item.data;
        var component = $('[name=' + item.type + ']')
        if (component)
            component.val(item.data)
    })
    if (majorTradeFirst != "") {
        $('[name=' + 2030 + ']').val(majorTradeFirst + "-" + tradeFirst);
    }
    if (majorTradeSecond != "") {
        $('[name=' + 2034 + ']').val(majorTradeSecond + "-" + tradeSecond);
    }
    if (companyLabels != "") {
        var arr = companyLabels.split("，");
        $.each(arr, function (i, item) {
            $('#company_labels_id').append("<a href='javascript:;' class='selected_company_labels'>" + item + "<i>&times;</i></a>");
        })
    }
}
//禁止编辑
function disablePage(barName) {
    $("#" + barName + " input").each(function (i, n) {
        $(n).attr("disabled", "disabled");
    })
    $("#" + barName + " select").each(function (i, n) {
        $(n).attr('disabled', true);
    })
    $("#" + barName + " textarea").each(function (i, n) {
        $(n).attr('disabled', true);
    })
    $('#' + barName + " a").each(function (i, n) {
        $(n).removeAttr('onclick');
        $(n).removeAttr('href')
    })
}
function initBoostrapSelect() {
    $('.selectpicker').selectpicker();
}

//初始化日期筛选
function initBoostrapDate() {
    //日期初始化
    var datetimepicker = $('.form_date').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition: "bottom-left"
    });
    return datetimepicker;
}

//初始化年月筛选
function initBootstrapDateMonth() {
    $('.form_date_month').datetimepicker({
        format: 'yyyy-mm',
        weekStart: 1,
        autoclose: true,
        todayBtn: 1,
        startView: 3,
        minView: 3,
        forceParse: false,
        language: 'zh-CN'
    });
}

//日期初始化
function initBoostrapDateWithHour() {
    var datetimepicker = $('.form_date').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd hh:ii",
        weekStart: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        maskInput: true,
        pickDate: true,
        hourStep: 1,
        minuteStep: 2,
        pickerPosition: "bottom-left"
    });
    return datetimepicker;
}
function initSearchToggle(table) {
    //搜索栏收缩按钮
    $(".search_toggle").click(function () { //收起展开查询条件
        $(".search_option").toggle();
        if (table)
            table.bootstrapTable('resetView');
    });
}

function checkDate(startId, endId, msg1, msg2, msg3) {
    var bol = true;
    var beginAt = $('#' + startId).val();
    var endAt = $('#' + endId).val();
    if (beginAt == null || beginAt == '') {
        var objtip = $('#' + startId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg1);
        bol = false;
    } else if (endAt == null || endAt == '') {
        var objtip = $('#' + startId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg2);
        bol = false;
    } else if (Date.parse(endAt) < Date.parse(beginAt)) {
        var objtip = $('#' + startId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg3);
        bol = false;
    } else {
        var objtip = $('#' + startId).parent().parent().find(".Validform_checktip");
        if (objtip.hasClass('Validform_wrong'))objtip.removeClass("Validform_wrong");
        objtip.text(" ");
        bol = true;
    }
    return bol;
}

function addFormError(startId, msg) {
    var objtip = $('#' + startId).parent().parent().find(".Validform_checktip");
    objtip.addClass("Validform_wrong");
    objtip.text(msg);
}
function addFormErrorLabel(startId, msg) {
    var objtip = $('#' + startId).parent().parent().parent().find(".Validform_checktip");
    objtip.addClass("Validform_wrong");
    objtip.text(msg);
}
function checkIsNotNull(id, msg) {
    var bol = true;
    var ipPositionType = $('#' + id).val();
    if (ipPositionType == null || ipPositionType == '') {
        var objtip = $('#' + id).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg);
        bol = false;
    } else {
        var objtip = $('#' + id).parent().parent().find(".Validform_checktip");
        if (objtip.hasClass('Validform_wrong'))objtip.removeClass("Validform_wrong");
        objtip.text(" ");
        bol = true;
    }
    return bol;
}
function checkIsNotNullForSelect(id, msg) {
    var bol = true;
    var ipPositionType = $('#' + id).val();
    if (ipPositionType == null || ipPositionType == '') {
        var objtip = $('#' + id).parent().parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg);
        bol = false;
    } else {
        var objtip = $('#' + id).parent().parent().find(".Validform_checktip");
        if (objtip.hasClass('Validform_wrong'))objtip.removeClass("Validform_wrong");
        objtip.text(" ");
        bol = true;
    }
    return bol;
}

function checkNumberCompare(firstId, lastId, msg1, msg2, msg3) {
    var bol = true;
    var first = $('#' + firstId).val();
    var last = $('#' + lastId).val();
    if (first == null || first == '') {
        var objtip = $('#' + firstId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg1);
        bol = false;
    } else if (last == null || last == '') {
        var objtip = $('#' + firstId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg2);
        bol = false;
    } else if (Number(first) > Number(last)) {
        var objtip = $('#' + firstId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg3);
        bol = false;
    } else {
        var objtip = $('#' + firstId).parent().parent().find(".Validform_checktip");
        if (objtip.hasClass('Validform_wrong'))objtip.removeClass("Validform_wrong");
        objtip.text(" ");
        bol = true;
    }
    return bol;
}

function checkRepeatPassWord(firstId, lastId, msg1) {
    var bol = true;
    var first = $('#' + firstId).val();
    var last = $('#' + lastId).val();
    if (first != last) {
        var objtip = $('#' + lastId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg1);
        bol = false;
    } else {
        var objtip = $('#' + lastId).parent().parent().find(".Validform_checktip");
        if (objtip.hasClass('Validform_wrong'))objtip.removeClass("Validform_wrong");
        objtip.text(" ");
        bol = true;
    }
    return bol;
}

function checkDeptTreeChecked(treeId, msg1) {
    var bol = true;
    if ($('#' + treeId).treeview('getChecked').length == 0) {
        var objtip = $('#' + treeId).parent().parent().find(".Validform_checktip");
        objtip.addClass("Validform_wrong");
        objtip.text(msg1);
        bol = false;
    } else {
        var objtip = $('#' + treeId).parent().parent().find(".Validform_checktip");
        if (objtip.hasClass('Validform_wrong'))objtip.removeClass("Validform_wrong");
        objtip.text(" ");
        bol = true;
    }
    return bol;
}
function intiValidForm(msg, o, cssctl) {
    if (!o.obj.is("form")) {//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
        if (o.type != 2) {
            var objtip = o.obj.parent().parent().find(".Validform_checktip");
            cssctl(objtip, o.type);
            objtip.text(msg);
        } else {
            var objtip = o.obj.parent().parent().find(".Validform_checktip");
            objtip.text(msg);
        }
    }
}
function initValidForm2(msg, o, cssctl) {
    if (!o.obj.is("form")) {//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
        if (o.type != 2) {
            var objtip = o.obj.parent().find(".Validform_checktip");
            cssctl(objtip, o.type);
            objtip.text(msg);
        } else {
            var objtip = o.obj.parent().find(".Validform_checktip");
            objtip.text(msg);
        }
    }
}

function selectRadio(name, value) {
    $('input[name="' + name + '"][value=' + value + ']').attr("checked", true);
}

var schoolData;
//初始化学校选择框{id：绑定的标签ID,selectMaxNum:最大选择数,callback:回调函数(参数是数组[{type:'',name:'',id:''}])}
function initIIInsomniaSchoolPicker(id, selectMaxNum, callback) {
    if ($('#' + id).attr('disablepop') != 'true') {
        if (selectMaxNum == "" || selectMaxNum == undefined || selectMaxNum == null) selectMaxNum = 7
        var schoolPicker = new SchoolPicker({
            data: schoolData,
            selectMaxNum: selectMaxNum,
            target: '#' + id,
            callback: function (schools) {
                if (callback) callback(schools);
            }
        });
        schoolPicker.init();
    }
}
var cityData;
//初始化省市选择框{id：绑定的标签ID,selectMaxNum:最大选择数,callback:回调函数}
function initIIInsomniaCityPicker(id, selectMaxNum, callback) {
    if ($('#' + id).attr('disablepop') != 'true') {
        if (selectMaxNum == "" || selectMaxNum == undefined || selectMaxNum == null) selectMaxNum = 7
        //页面初始化加载省市数据
        getAsyncJSON("/common/findChineseProvince", {"type": 17}, function (data) {
            cityData = data;
            var cityPicker = new IIInsomniaCityPicker({
                data: cityData,
                selectMaxNum: selectMaxNum,
                target: '#' + id,
                callback: function (citys, ids) {
                    if (callback) callback(citys, ids);
                }
            });
            cityPicker.init();
        });
    }
}
var majorData;
//初始化专业选择框{id：绑定的标签ID,selectMaxNum:最大选择数,callback:回调函数}
function initIIInsomniaMajorPicker(id, selectMaxNum, callback) {
    if ($('#' + id).attr('disablepop') != 'true') {
        if (selectMaxNum == "" || selectMaxNum == undefined || selectMaxNum == null) selectMaxNum = 7
        var majorPicker = new MajorPicker({
            data: majorData,
            selectMaxNum: selectMaxNum,
            target: '#' + id,
            callback: function (majors, ids) {
                if (callback) callback(majors, ids);
            }
        });
        majorPicker.init();
    }
}

var labelData;
//初始化标签选择框{id:绑定的标签ID,selectMaxNum:最大选择数,type:标签类型(职位，简历),callback:回调函数}
function initIIInsomniaLabelPicker(id, selectMaxNum, type, callback) {
    if ($('#' + id).attr('disablepop') != 'true') {
        if (selectMaxNum == "" || selectMaxNum == undefined || selectMaxNum == null) selectMaxNum = 7
        var labelPicker = new LabelPicker({
            data: labelData,
            selectMaxNum: selectMaxNum,
            type: type,
            target: '#' + id,
            callback: function (labels, ids) {
                if (callback) callback(labels, ids);
            }
        });
        labelPicker.init();
    }
}

//点击弹出职位类别选择框{id:绑定的标签ID,callback:回调函数(positoinType:职位中文名称,positionTypeId:职位ID,positionTopType:一级职位名称)}
function initIIInsomniaPositionTypePicker(id, callback) {
    $('#' + id).click(function (event) {
        if ($('#' + id).attr('disablepop') != 'true') {
            var fisrtLevelContent = $.trim($('#positionTypeFirstLevel').html());
            if (fisrtLevelContent.length == 0)
                showFirstLevel();
            $('#positionModal').modal('show');
        }
    })
    $(document).on('click', '.positionTypeThirdLevel', function (event) {
        $(this).parent().parent().find('.current').removeClass('current');
        $(this).parent().addClass('current');
        var positoinType = $(this)[0].innerHTML;
        var positionTypeId = $(this).attr("optId");
        var positionTopType = $('#positionTypeFirstLevel .current').children().text();
        if (callback) callback(positoinType, positionTypeId, positionTopType);
        $('#positionModal').modal('hide');
    })
}

function initIIInsomniaSendSMSModal(id) {
    $('#' + id).click(function (event) {
        $('#sendSMSModal').modal('show');
    })
}

function initIIInsomniaSendMailModal(id) {
    $('#' + id).click(function (event) {
        $('#sendMailModal').modal('show');
    })
}

//调整bootstrap table 高度
function resizeTableHeight(table, diffHeight) {
    var height = $(window).height();
    var alertTopHeight = $('#topAlert').length > 0 ? 46 : 0;
    table.bootstrapTable('resetView', {height: height - diffHeight - alertTopHeight});
}

//弹出部门选择树
function popDeptTree(singleChecked) {
    $('#commModel').removeData('bs.modal');
    $('#commModel').modal({
        show: true,
        backdrop: 'static',
        remote: '/common/popDeptTree?singleChecked=' + (singleChecked && singleChecked == 'true' ? 'true' : 'false')
    });
}

//弹出全屏窗体
function windowOpenFullScreen(path, name) {
    var doc = documentSize();
    var width = Math.max(Math.max(doc.width, $(window).innerWidth()), window.screen.width) - 15;
    var height = Math.max(Math.max(doc.height, $(window).innerHeight()), window.screen.height) - 110;
    return windowOpen(path, name, width, height, 0, 0);
}

//弹出窗体在中间
function windowOpenCenter(path, name, width, height) {
    var doc = documentSize();
    var windowWidth = Math.max(Math.max(doc.width, $(window).innerWidth()), window.screen.width);
    var windowHeight = Math.max(Math.max(doc.height, $(window).innerHeight()), window.screen.height);
    var top = (windowHeight - height - 50) / 2 - 20;
    var left = (windowWidth - width) / 2;
    return windowOpen(path, name, width, height, top, left);
}

//弹出窗体隐藏Title
function windowOpenFullScreenHideTitle(path, name) {
    return window.open(path, name, 'fullscreen=yes,directories=no,status=no,toolbar=no,scroll=no,help=no,width=800px,height=600px');
}

//弹出窗体
function windowOpen(path, name, width, height, top, left) {
    return window.open(path, name,
        'height=' + height + 'px,width=' + width + 'px,top=' + top + ',left=' + left +
        ',toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
}

function documentSize() {
    var doc = new Object();
    var body = (document.compatMode && document.compatMode.toLowerCase() == "css1compat") ? document.documentElement
        : document.body;
    if (isNaN($(window).innerHeight()) || isNaN($(window).innerWidth())) {
        doc.height = body.clientHeight;
        doc.width = body.clientWidth;
        doc.mode = "document";
    } else {
        doc.height = $(window).innerHeight();
        doc.width = $(window).innerWidth();
        doc.mode = "window";
    }
    return doc;
}
